package com.suge.notify.taobao.seller;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.suge.order.dao.dataobject.SmsOrderDO;
import com.suge.order.manager.SmsOrderManager;
import com.suge.user.dao.dataobject.UserDO;
import com.suge.user.manager.UserManager;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.NotifyItem;
import com.taobao.api.domain.NotifyRefund;
import com.taobao.api.domain.NotifyTrade;
import com.taobao.api.internal.parser.json.JsonConverter;
import com.taobao.api.internal.stream.message.TopCometMessageListener;
import com.taobao.api.internal.util.json.JSONValidatingReader;
import com.taobao.api.request.LogisticsOrdersGetRequest;
import com.taobao.api.response.LogisticsOrdersGetResponse;

public class SmsMessageProcessor implements TopCometMessageListener{

	public static final String NOTIFY_TRADE = "notify_trade";
	public static final String NOTIFY_ITEM = "notify_item";
	public static final String NOTIFY_REFUND = "notify_refund";
	private static final String appKey="21430427";
	
	private static final String appSecret = "89fbda48de40e8833e8e0289919a4e06";
	
	private static final String tbUrl = "http://gw.api.taobao.com/router/rest";
	private static final Logger logger = LoggerFactory.getLogger(SmsMessageProcessor.class);
	private SmsOrderManager  smsOrderManager;
	@Autowired
	private UserManager userManager;

	public void onConnectMsg(String message) {
		
		logger.error("Receive onConnectMsg:"+message);
		
	}

	public void onHeartBeat() {
		logger.error("Receive onHeartBeat message");
	}

	public void onReceiveMsg(String message) {
		
		logger.error("Receive message:"+message);
		
		NotifyTrade  tradeMessage=  (NotifyTrade) decodeMsg(message);
		
		smsOrderManager.insertSmsOrder(convertMessageToOrder(tradeMessage));
		
	}

	public void onDiscardMsg(String message) {
		// TODO Auto-generated method stub	
	}

	public void onServerUpgrade(String message) {
		// TODO Auto-generated method stub
	}

	public void onServerRehash() {
		// TODO Auto-generated method stub	
	}

	public void onServerKickOff() {
		// TODO Auto-generated method stub	
	}

	public void onClientKickOff() {
		// TODO Auto-generated method stub	
	}

	public void onOtherMsg(String message) {
		// TODO Auto-generated method stub
	}

	public void onException(Exception e) {
		// TODO Auto-generated method stub
	}

	public void setSmsOrderManager(SmsOrderManager smsOrderManager) {
		this.smsOrderManager = smsOrderManager;
	}

	public SmsOrderManager getSmsOrderManager() {
		return smsOrderManager;
	}

	/**
	 * Item,refund,trade
	 */
	private static Object decodeMsg(String msg){
		JSONValidatingReader reader = new JSONValidatingReader();
		Object rootObj = reader.read(msg);
		if (rootObj instanceof Map<?, ?>) {
			Map<?, ?> rootJson = (Map<?, ?>) rootObj;
			Class<?> clazz = null;
			if (rootJson.containsKey(NOTIFY_ITEM)) {
				clazz = NotifyItem.class;
			} else if (rootJson.containsKey(NOTIFY_TRADE)) {
				clazz = NotifyTrade.class;
			} else if (rootJson.containsKey(NOTIFY_REFUND)) {
				clazz = NotifyRefund.class;
			}

			if (clazz != null && !rootJson.isEmpty()) {
				rootJson.values().iterator().next();
				Map<?, ?> rspJson = (Map<?, ?>) rootJson.values().iterator().next();
				JsonConverter jc = new JsonConverter();
				try {
					return jc.fromJson(rspJson, clazz);
				} catch (ApiException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	private SmsOrderDO convertMessageToOrder(NotifyTrade notifyTrade){
		
		SmsOrderDO smsOrderDO  = new SmsOrderDO();
		if(notifyTrade!=null){
			smsOrderDO.setAttribute(notifyTrade.getStatus());
			smsOrderDO.setFailReason("");
			smsOrderDO.setMemo("");
			//smsOrderDO.setOrderId(0);
			smsOrderDO.setOuterOrderId(String.valueOf(notifyTrade.getOid()));
			smsOrderDO.setSoldPrice(0);
			smsOrderDO.setStandardCostPrice(4);
			smsOrderDO.setStatus(0);
			smsOrderDO.setSupplierId(1);
			smsOrderDO.setSupplierNick("tx");
			smsOrderDO.setUserBizorderId(-1);
			smsOrderDO.setOrderType(convertStatus2Int(notifyTrade.getStatus()));
			smsOrderDO.setUserNick(notifyTrade.getSellerNick());
			smsOrderDO.setBuyerNick(notifyTrade.getBuyerNick());
			UserDO userDO = userManager.getAppUserByUserNick(notifyTrade.getSellerNick());
			
			TaobaoClient client=new DefaultTaobaoClient(tbUrl, appKey, appSecret);
			LogisticsOrdersGetRequest req=new LogisticsOrdersGetRequest();
			req.setFields("tid,seller_nick,buyer_nick,delivery_start,sub_tids,is_spilt,company_name,receiver_name");
			req.setTid(notifyTrade.getTid());
			req.setBuyerNick(notifyTrade.getBuyerNick());

			try {
				LogisticsOrdersGetResponse response = client.execute(req , userDO.getSessionKey());
				if(response.isSuccess()){
					smsOrderDO.setBuyerRealName(response.getShippings().get(0).getReceiverName());
				}
			} catch (ApiException e) {
				e.printStackTrace();
			}
			
		}
		return smsOrderDO;
	}
	
	private int convertStatus2Int(String staus){
		if("TradeSellerShip".equals(staus)){
			return 1;
		}
		else if("TradeSellerShip".equals(staus)){
			
		}
		else if("TradeSellerShip".equals(staus)){
			
		}
		else if("TradeSellerShip".equals(staus)){
			
		}
		else if("TradeSellerShip".equals(staus)){
			
		}

		return -1;
	}
	public UserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

}
